import type { Directive, DirectiveBinding } from 'vue'

function checkPermission(el: HTMLElement, binding: DirectiveBinding) {
  const permissionStore = usePermissionStore()
  const { value } = binding

  if (value) {
    const hasAuth = permissionStore.hasPermission(value)
    if (!hasAuth) {
      el.parentNode ? el.parentNode.removeChild(el) : (el.style.display = 'none')
    }
  }
  else {
    throw new Error('need roles! Like v-permission="[\'admin\',\'editor\']"')
  }
}

export default {
  name: 'permission',
  directive: {
    mounted(el, binding) {
      checkPermission(el, binding)
    },
    updated(el, binding) {
      checkPermission(el, binding)
    },
  } as Directive,
}
